package com.whfc.wxmp.api.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.github.pagehelper.util.StringUtil;
import com.whfc.base.entity.AppMessage;
import com.whfc.base.service.MessageService;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.*;
import com.whfc.common.result.PageData;
import com.whfc.emp.dto.*;
import com.whfc.emp.entity.*;
import com.whfc.emp.entity.AppWorkPlan;
import com.whfc.emp.enums.EmpHealthInfoType;
import com.whfc.emp.service.*;
import com.whfc.entity.dto.Apply.rep.*;
import com.whfc.entity.dto.Apply.req.*;
import com.whfc.entity.dto.msg.AppMsgToUserDTO;
import com.whfc.entity.dto.msg.PushMsgDTO;
import com.whfc.fuum.dto.SysDeptDTO;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.entity.WxUser;
import com.whfc.fuum.service.SysDeptService;
import com.whfc.fuum.service.SysUserService;
import com.whfc.mach.entity.AppMach;
import com.whfc.mach.service.AppMachService;
import com.whfc.wxmp.api.sys.service.WxApplyService;
import com.whfc.wxmp.dto.ApprovalRecordDTO;
import com.whfc.wxmp.dto.EntryApplicationDTO;
import com.whfc.wxmp.dto.EntryApplicationDetailRep;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class WxApplyServiceImpl implements WxApplyService {

    @DubboReference(interfaceClass = AppEntryApplicationService.class, version = "1.0.0", timeout = 30000)
    private AppEntryApplicationService appEntryApplicationService;

    @DubboReference(interfaceClass = AppEmpService.class, version = "1.0.0", timeout = 30000)
    private AppEmpService appEmpService;

    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0", timeout = 30000)
    private SysDeptService sysDeptService;

    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0", timeout = 30000)
    private SysUserService sysUserService;

    @DubboReference(interfaceClass = MessageService.class, version = "1.0.0", timeout = 30000)
    private MessageService messageService;

    @DubboReference(interfaceClass = ApprovalRecordService.class, version = "1.0.0", timeout = 30000)
    private ApprovalRecordService approvalRecordService;

    @DubboReference(interfaceClass = AppWorkPlanService.class, version = "1.0.0", timeout = 30000)
    private AppWorkPlanService appWorkPlanService;

    @DubboReference(interfaceClass = AppContractService.class, version = "1.0.0", timeout = 30000)
    private AppContractService appContractService;

    @DubboReference(interfaceClass = AppEmpHealthReportService.class, version = "1.0.0", timeout = 30000)
    private AppEmpHealthReportService appEmpHealthReportService;


    @DubboReference(interfaceClass = AppEmpWorkService.class, version = "1.0.0", timeout = 30000)
    private AppEmpWorkService appEmpWorkService;

    @DubboReference(interfaceClass = PlanCategoryService.class, version = "1.0.0", timeout = 30000)
    private PlanCategoryService planCategoryService;

    @DubboReference(interfaceClass = AppMachService.class, version = "1.0.0", timeout = 30000)
    private AppMachService appMachService;

    @DubboReference(interfaceClass = ClassMeetingService.class, version = "1.0.0", timeout = 30000)
    private ClassMeetingService classMachService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public String saveApplyPersonnel(WxUser user, AppEntryApplicationDTO req) {

        // 存储入场申请记录
        AppEntryApplicationDTO AppEntryApplicationDTO = appEntryApplicationService.saveApply(user.getId(),req);
        if(AppEntryApplicationDTO.getId() == null){
            return "提交失败";
        }

        // 添加入场工种
        if(StringUtil.isNotEmpty(req.getEntryCategoryName())){
            PlanCategory pg = new PlanCategory();
            pg.setPlanId(AppEntryApplicationDTO.getId());
            pg.setCategoryName(req.getEntryCategoryName());
            pg.setCreateUser(user.getId());
            planCategoryService.add(pg);
        }
        // 查询项目下的个个机构管理人员
        List<UserDeptDTO> userDeptDTOS = sysDeptService.queryMessage(req.getDeptId());
        List<AppMessage> appMessages = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userDeptDTOS)) {
            for (UserDeptDTO userDept : userDeptDTOS) {
                if(Objects.equals(userDept.getUserType(), SysUserUserType.OWNER.getValue()) || Objects.equals(userDept.getUserType(),SysUserUserType.SUPERVISOR.getValue())){
                    // 存储审核信息
                    ApprovalRecord approvalRecord = new ApprovalRecord();
                    approvalRecord.setApplicationId(AppEntryApplicationDTO.getId());
                    approvalRecord.setApproverType(userDept.getUserType());
                    approvalRecord.setApproverId(userDept.getUserId());
                    approvalRecord.setReviewType(ReviewType.ENTRANCE_REVIEW.getValue());
                    approvalRecord.setApprovalResult(ApprovalResult.PENDING.getValue());
                    approvalRecordService.insertApprovalRecord(approvalRecord);

                    // 人员入场申给审批人发送消息提醒
                    buildMessage(userDept, appMessages);
                }
            }
        }
//        messageService.addAppMessage(appMessages);
        return "提交成功";
    }

    private void buildMessage(UserDeptDTO userDept, List<AppMessage> appMessages) {
        if (userDept == null || userDept.getUserType().equals(SysUserUserType.COMMON.getValue())) return;
        
        // 创建接收人列表
        List<AppMsgToUserDTO> toUserList = new ArrayList<>();
        AppMsgToUserDTO userDTO = new AppMsgToUserDTO();
        userDTO.setUserId(userDept.getUserId());
        userDTO.setUsername(userDept.getUserName());
        userDTO.setPhone(userDept.getPhone());
        userDTO.setDeptId(userDept.getDeptId());
//        userDTO.setDeptName(userDept.getDeptName());
        toUserList.add(userDTO);
        
        // 创建推送消息DTO
        PushMsgDTO pushMsgDTO = new PushMsgDTO();
        pushMsgDTO.setTitle("人员入场审批");
        pushMsgDTO.setContent("您有需要审批的单子请及时处理");
        pushMsgDTO.setDeptId(userDept.getDeptId());
        pushMsgDTO.setTime(new Date());
        pushMsgDTO.setModuleType(10);
        pushMsgDTO.setMsgObjectId("1");
        pushMsgDTO.setToUserList(toUserList);
        
        // 设置消息渠道：PC(3)和APP(1)
        List<Integer> msgChannelList = new ArrayList<>();
        msgChannelList.add(3); // PC
        msgChannelList.add(1); // APP
        pushMsgDTO.setMsgChannelList(msgChannelList);
        
        // 通过MQ发送消息
        amqpTemplate.convertAndSend(QueueConst.PUSH_MSG_EXCHANGE, "", JSON.toJSONString(pushMsgDTO));
        
        // 保留原有的AppMessage构建逻辑，用于兼容性
//        AppMessage appMessage = new AppMessage();
//        appMessage.setContent("您有需要审批的单子请及时处理");
//        appMessage.setDeptId(userDept.getDeptId());
//        appMessage.setTitle("人员入场审批");
//        appMessage.setToUserId(userDept.getUserId());
//        appMessage.setToUserName(userDept.getUserName());
//        appMessage.setToUserPhone(userDept.getPhone());
//        appMessage.setMsgType(AppWarnModuleType.MACH.value());
//        appMessage.setMsgChannel(AppWarnMsgChannel.WXMP.value());
//        appMessage.setMsgObjectId("1");
//        appMessage.setModuleType(10);
//        appMessage.setTime(new Date());
//        appMessage.setState(0);
//        appMessage.setDelFlag(0);
//        appMessage.setCreateTime(new Date());
//        appMessage.setUpdateTime(new Date());
//        appMessages.add(appMessage);
//
//        AppMessage msMessage = new AppMessage();
//        msMessage.setContent("您有需要审批的单子请及时处理");
//        msMessage.setDeptId(userDept.getDeptId());
//        msMessage.setTitle("人员入场审批");
//        msMessage.setToUserId(userDept.getUserId());
//        msMessage.setToUserName(userDept.getUserName());
//        msMessage.setToUserPhone(userDept.getPhone());
//        msMessage.setMsgType(AppWarnModuleType.MACH.value());
//        msMessage.setMsgChannel(AppWarnMsgChannel.MS.value());
//        msMessage.setMsgObjectId("1");
//        msMessage.setModuleType(10);
//        msMessage.setTime(new Date());
//        msMessage.setState(0);
//        msMessage.setDelFlag(0);
//        msMessage.setCreateTime(new Date());
//        msMessage.setUpdateTime(new Date());
//        appMessages.add(msMessage);
    }

    @Override
    public List<SafetyTrainingExamReq> queryPersonnel(QueryPersonnelReq req) {
        // 获取非系统人员信息
        List<AppEmpDTO> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(req.getEmpNames())){
            for (String empName : req.getEmpNames()) {
                if ("".equals(empName)){
                    continue;
                }
                list.addAll(appEmpService.list(req.getDeptId(), empName));
                if (CollectionUtils.isEmpty(list)) {
                    return null;
                }
            }

        }
        List<SafetyTrainingExamReq> safetyTrainingExamReqs = new ArrayList<>();
        List<QueryEmpSysIdDto> appEmpIds = null;
        if(CollectionUtils.isEmpty(list)){
            appEmpIds = sysUserService.getAppEmps(null,req.getDeptId());
        }else {
            for(AppEmpDTO appEmpDTO : list){
                appEmpIds = sysUserService.getAppEmps(appEmpDTO.getEmpId(),req.getDeptId());
            }

        }

        for (QueryEmpSysIdDto queryEmpSysId : appEmpIds) {
            AppEmpDTO empInfo = appEmpService.getEmpInfo(queryEmpSysId.getAppEmpId());
            empInfo.setEmpId(queryEmpSysId.getSysUserId());
            SafetyTrainingExamReq safetyTrainingExamReq = convertToExamReq(empInfo);
            safetyTrainingExamReqs.add(safetyTrainingExamReq);
        }
        return safetyTrainingExamReqs;
    }

    private List<Map<String, String>> convertAttachList(List<AppAttachDTO> attachList) {
        // 空集合直接返回空列表，避免后续流处理空指针
        if (CollectionUtils.isEmpty(attachList)) {
            return Collections.emptyList();
        }

        return attachList.stream()
                .filter(Objects::nonNull)
                .filter(dto ->
                        // 统一过滤条件：name和url非空且非空白
                        dto.getName() != null && !dto.getName().trim().isEmpty() &&
                                dto.getUrl() != null && !dto.getUrl().trim().isEmpty()
                )
                .map(dto -> {
                    Map<String, String> map = new HashMap<>(2);
                    map.put("name", dto.getName().trim());
                    map.put("url", dto.getUrl().trim());
                    return map;
                })
                .collect(Collectors.toList());
    }

    private SafetyTrainingExamReq convertToExamReq(AppEmpDTO empDTO) {
        SafetyTrainingExamReq req = new SafetyTrainingExamReq();

        // 基础信息映射
        req.setEmp_id(empDTO.getEmpId());
        req.setName(empDTO.getEmpName());
        req.setGender(convertGender(empDTO.getGender()));
        req.setCompany(empDTO.getCorpName());
        req.setPosition(empDTO.getWorkTypeName());
        req.setAddress(empDTO.getAddress());
        req.setHardwareNumber(empDTO.getSn());
        req.setAvatar(empDTO.getAvatar());
        req.setExamStatus("未考试");
        PlanCategory byId = planCategoryService.getById(empDTO.getEmpId());
        if(byId != null){
            req.setEntryCategoryName(byId.getCategoryName());
        }

        // 合同信息
        List<AppEmpContractDTO> contractDTOs = appContractService.list(empDTO.getEmpId());
        req.setContractFileName(convertAttachList(contractDTOs.isEmpty()?null:contractDTOs.get(0).getFileAttachList()));

        // 资质证书信息
        List<AppEmpCertDTO> list = appEmpService.certList(empDTO.getEmpId());
        req.setQualificationCertificateNmae(convertAttachList(!list.isEmpty() ? list.get(0).getFileAttachList() : null));

        // 体检报告（类型1）
        PageData<AppEmpHealthReportDTO> pageData = appEmpHealthReportService.list(empDTO.getEmpId(), EmpHealthInfoType.JOURNEY_CARD, 1, 1);
        List<AppEmpHealthReportDTO> insuranceDTOs = pageData.getList();
        List<Map<String,String>> medicalReportNmae = new ArrayList<>();
        if(!CollectionUtils.isEmpty(insuranceDTOs) && !insuranceDTOs.get(0).getImgList().isEmpty()){
            Map<String,String> map = new HashMap<>();
            map.put(insuranceDTOs.get(0).getType(), insuranceDTOs.get(0).getImgList().get(0));
            medicalReportNmae.add(map);
        }
        req.setMedicalReportNmae(medicalReportNmae);

        // 社保证明（类型2）
        PageData<AppEmpHealthReportDTO> healthReportDTOPageData = appEmpHealthReportService.list(empDTO.getEmpId(), EmpHealthInfoType.HEALTH_CODE, 1, 1);
        List<AppEmpHealthReportDTO> healthReportDTOS = healthReportDTOPageData.getList();
        List<Map<String,String>> socialSecurityProofNmae = new ArrayList<>();
        if(!CollectionUtils.isEmpty(healthReportDTOS) && !healthReportDTOS.get(0).getImgList().isEmpty()){
            Map<String,String> map = new HashMap<>();
            map.put(healthReportDTOS.get(0).getType(), healthReportDTOS.get(0).getImgList().get(0));
            socialSecurityProofNmae.add(map);
        }
        req.setSocialSecurityProofNmae(socialSecurityProofNmae);

        return req;
    }

    /**
     * 性别转换工具方法
     */
    private String convertGender(Integer gender) {
        return gender == null ? "未知" :
                gender == 1 ? "男" :
                        gender == 2 ? "女" : "未知";
    }

    @Override
    public List<InstitutionRep> queryInstitution(WxUser user,Integer deptId) {
        if (user == null) {
            return Arrays.asList();
        }
        return sysDeptService.getUnit(deptId);
    }

    @Override
    public List<EntryApplicationDTO> entryReview(WxUser user, ApprovalRecordReq req) {
        List<EntryApplicationDTO> recordReps = new ArrayList<>();
        if(req.getId() == null){
            // 查询当前登录账号的申请记录
            List<Integer> applicationIds = new ArrayList<>();
            SysUser sysUser = sysUserService.getUserById(user.getId());
            if (sysUser == null || sysUser.getUserType() == null || sysUser.getUserType().equals(SysUserUserType.COMMON.getValue())) {
                return null;
            }
            // 获取机构
            String integers = sysDeptService.selectDeptIdById(user.getId());
            List<Integer> pidList = Optional.ofNullable(integers)
                    .filter(StringUtils::isNotBlank)
                    .map(str -> str.split(","))
                    .map(Arrays::stream)
                    .orElseGet(Stream::empty)
                    .map(StringUtils::trim)
                    .filter(StringUtils::isNotBlank)
                    .map(str -> {
                        try {
                            return Integer.valueOf(str);
                        } catch (NumberFormatException e) {
                            System.out.println("跳过无效数字格式：" + str);
                            return null;
                        }
                    })
                    .filter(java.util.Objects::nonNull)
                    .collect(Collectors.toList());
            List<EntryAuditRep> entryAuditReps = approvalRecordService.entryReview(pidList,user.getId());
            applicationIds.addAll(entryAuditReps.stream().map(EntryAuditRep::getEntryApplicationId).collect(Collectors.toList()));
            Set<Integer> tempSet = new HashSet<>(applicationIds);
            applicationIds = new ArrayList<>(tempSet);
            for (Integer applicationId : applicationIds) {
                EntryApplicationDTO ret = getByEntryApplicationId(applicationId, req.getIsReview(), user.getId());
                if (ret != null) {
                    recordReps.add(ret);
                }
            }
        } else {
            EntryApplicationDTO ret = getByEntryApplicationId(req.getId(), req.getIsReview(), user.getId());
            if (ret != null) {
                recordReps.add(ret);
            }
        }
        recordReps = recordReps.stream()
                .sorted(Comparator.comparing(EntryApplicationDTO::getEntryApplicationId).reversed())
                .collect(Collectors.toList());
        return recordReps;
    }

    /**
     * 根据申请id查询申请审核记录
     * @param
     * @return
     */
    private EntryApplicationDTO getByEntryApplicationId(Integer entryApplicationId, Integer reviewType, Integer currentUserId) {
        EntryApplicationDTO recordRep = new EntryApplicationDTO();
        recordRep.setEntryApplicationId(entryApplicationId);
        recordRep.setFlag(false);
        // 1、根据申请记录id查询申请记录
        AppEntryApplication appEntryApplication = appEntryApplicationService.selectByPrimaryKey(entryApplicationId);
        if (appEntryApplication == null) {
            return null;
        }
        recordRep.setTeamLeader(appEmpService.getEmpInfo(appEntryApplication.getTeamLeaderId()));
        String[] entryPersonIds = appEntryApplication.getEntryPersonId().split("/");
        List<SysUser> enteryPersonList = new ArrayList<>();
        for (String entryPersonId : entryPersonIds){
            enteryPersonList.add(sysUserService.getUserById(Integer.parseInt(entryPersonId)));
        }
        recordRep.setEntryPersons(enteryPersonList);
        SysUser applicant = null;//申请人
        // 2、根据申请人id查询申请人信息
        if (!StringUtils.isEmpty(appEntryApplication.getCreateUser())) {
            applicant = sysUserService.getUserById(Integer.parseInt(appEntryApplication.getCreateUser()));
        }
        recordRep.setEntryApply(appEntryApplication);
        Map<Integer, Boolean> needApproval = new HashMap<>();
        // 2、根据申请记录id和审核类型查询审核记录
        List<ApprovalRecordDTO> approvalRecords = new ArrayList<>();
        List<ApprovalRecord> approvalRecordList = approvalRecordService.selectRecordByApplyIdAndAuditType(entryApplicationId, reviewType);
        for (ApprovalRecord approvalRecord : approvalRecordList) {
            ApprovalRecordDTO recordDTO = new ApprovalRecordDTO();
            BeanUtils.copyProperties(approvalRecord, recordDTO);
            recordDTO.setApplicantUser( applicant);
            // 4、根据审核人id查询审核人信息
            SysUser approvalUser = sysUserService.getUserById(approvalRecord.getApproverId());
            if (approvalUser == null || approvalUser.getUserType() == null) continue;
            recordDTO.setApprovalUser(approvalUser);
            approvalRecords.add(recordDTO);
            if (approvalRecord.getApprovalResult().equals(ApprovalResult.PENDING.getValue())
                    && (!needApproval.containsKey(approvalUser.getUserType()) || needApproval.get(approvalUser.getUserType()) != false)
                ){
                needApproval.put(approvalUser.getUserType(), true);
            } else if (approvalRecord.getApprovalResult().equals(ApprovalResult.APPROVE.getValue())) {
                needApproval.put(approvalUser.getUserType(), false);
            }
        }
        // 按审核人类型倒序排列
        approvalRecords.sort((o1, o2) -> o2.getApprovalUser().getUserType() - o1.getApprovalUser().getUserType());
        // 简易版工作流 计算当前审核节点
        Integer approvalStep = SysUserUserType.SUPERVISOR.getValue();
        needApproval = needApproval.entrySet().stream()
                .sorted(Map.Entry.<Integer, Boolean>comparingByKey().reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1, // 合并函数，如果有重复key
                        LinkedHashMap::new // 保持排序顺序
                )); //按照key倒序排列
        Optional<Integer> firstFalseKey = needApproval.entrySet()
                .stream()
                .filter(Map.Entry::getValue) // value == true
                .map(Map.Entry::getKey)
                .findFirst();
        if (firstFalseKey.isPresent()) {
            approvalStep = firstFalseKey.get();
        }
        // 设置当前审核节点审核人员审核权限
        for (ApprovalRecordDTO dto : approvalRecords){
            if (dto.getApprovalResult().equals(ApprovalResult.PENDING.getValue()) && dto.getApprovalUser().getUserType().equals(approvalStep)){
                dto.setFlag(true);
                if (dto.getApprovalUser().getId().equals(currentUserId)){
                    recordRep.setFlag(true);
                }
            }else {
                dto.setFlag(false);
            }
        }
        recordRep.setApprovalRecords(approvalRecords);
        return recordRep;
    }

    @Override
    public String applyEntryReview(WxUser user, Integer approvalResult, Integer id) {
        // 获取当前审核记录
        ApprovalRecord currentRecord = approvalRecordService.getApprovalRecordById(id);
        if(approvalResult.equals(ApprovalResult.APPROVE.getValue())){
            // 当前节点审批通过
            currentRecord.setApprovalResult(ApprovalResult.APPROVE.getValue());
            currentRecord.setApprovalTime(new Date());
            approvalRecordService.updateApprovalRecord(currentRecord);
            // 查看是否还有下一个节点
            Integer nextNode = getNextNode(currentRecord.getApproverType());
//            List<ApprovalRecord> previousNodes = approvalRecordService.getParentNode(nextNode, currentRecord.getApplicationId());
            AppEntryApplication entryApplication = appEntryApplicationService.selectByPrimaryKey(currentRecord.getApplicationId());
            if (nextNode == null) {
                // 没有下一个审核节点，申请审核通过
                entryApplication.setApprovalStatus(ApprovalResult.APPROVE.getValue());
                appEntryApplicationService.updateApprovalResult(entryApplication);
            }else if(entryApplication.getApprovalStatus().equals(ApprovalResult.PENDING.getValue())){
                entryApplication.setApprovalStatus(ApprovalResult.APPROVING.getValue());
                appEntryApplicationService.updateApprovalResult(entryApplication);
            }
            // 设置同类型其余审核记录：无需审核
            List<ApprovalRecord> approvalRecordList = approvalRecordService.selectRecordByApplyIdAndAuditType(currentRecord.getApplicationId(), ReviewType.ENTRANCE_REVIEW.getValue());
            for (ApprovalRecord record: approvalRecordList){
                if (record.getApproverType().equals(currentRecord.getApproverType())){
                    if (!currentRecord.getId().equals(record.getId())) {
                        record.setApprovalResult(ApprovalResult.COMPLETED.getValue());
                        record.setApprovalTime(new Date());
                        approvalRecordService.updateApprovalRecord(record);
                    }
                }
            }
        } else if(approvalResult.equals(ApprovalResult.REJECT.getValue())){
            // 当前审批节点
            currentRecord.setApprovalResult(ApprovalResult.REJECT.getValue());
            currentRecord.setApprovalTime(new Date());
            approvalRecordService.updateApprovalRecord(currentRecord);
            // 申请记录
            AppEntryApplication entryApplication = appEntryApplicationService.selectByPrimaryKey(currentRecord.getApplicationId());
            entryApplication.setApprovalStatus(ApprovalResult.REJECT.getValue());
            appEntryApplicationService.updateApprovalResult(entryApplication);
        }
        return "审核成功!";
    }

    /**
     * 处理顶级节点审核（直接决定申请最终状态）
     */
    private void handleTopNodeAudit(ApprovalRecord record, Integer approvalResult, AuditStrategy strategy) {
        // 更新当前审核记录结果
        record.setApprovalResult(approvalResult);
        approvalRecordService.updateApprovalRecord(record);

        // 更新申请状态
        if (Objects.equals(approvalResult, 0)) {
            strategy.updateApplicationStatus(0);
        } else {
            strategy.updateApplicationStatus(1);
        }
    }

    /**
     * 处理非顶级节点审核
     */
    private void handleNonTopNodeAudit(ApprovalRecord currentRecord, Integer approvalResult,
                                       Integer nextNode, AuditStrategy strategy, Integer reviewType) {
        // 更新当前审核记录
        currentRecord.setApprovalResult(approvalResult);
        approvalRecordService.updateApprovalRecord(currentRecord);

        // 处理拒绝逻辑：终止后续节点，更新申请状态为拒绝
        if (Objects.equals(approvalResult, 0)) {
            terminateSubsequentNodes(currentRecord.getApplicationId());
            strategy.updateApplicationStatus(0);
            return;
        }

        // 如果是最终节点（如业主），则更新申请为通过
        if(Objects.equals(nextNode,1) && Objects.equals(approvalResult, "1")){
            strategy.updateApplicationStatus(1);
        }
    }
    /**
     * 终止后续节点
     */
    private void terminateSubsequentNodes(Integer applicationId) {
        List<ApprovalRecord> subsequentNodes = approvalRecordService.getParentNode(null, applicationId);
        if (!CollectionUtils.isEmpty(subsequentNodes)) {
            subsequentNodes.stream()
                    .filter(node -> node.getApprovalResult() == 2)
                    .forEach(node -> {
                        node.setApprovalResult(3);
                        approvalRecordService.updateApprovalRecord(node);
                    });
        }
    }


    /**
     * 检查上一节点状态
     */
    private String checkPreviousNodeStatus(Integer nextNode, Integer applicationId) {
        List<ApprovalRecord> previousNodes = approvalRecordService.getParentNode(nextNode, applicationId);
        if (CollectionUtils.isEmpty(previousNodes)) {
            return null;
        }

        // 检查是否有上一节点未审核或已拒绝
        boolean hasPendingOrRejected = previousNodes.stream()
                .anyMatch(node -> node.getApprovalResult() == 2
                        || node.getApprovalResult() == 0);
        if (!hasPendingOrRejected) {
            return "您还不能审批，上一节点未完成审核或已拒绝!";
        }
        return null;
    }

    /**
     * 根据审核类型获取对应的处理策略
     */
    private AuditStrategy getAuditStrategy(Integer reviewType, Integer applicationId) {

        switch (reviewType) {
            case 1:
                // 入场审核
                AppEntryApplication entryApp = appEntryApplicationService.selectByPrimaryKey(applicationId);
                return new AuditStrategy(
                        entryApp,
                        new Consumer2<Object, Integer>() {  // 使用自定义的Consumer2接口
                            @Override
                            public void accept(Object app, Integer status) {
                                ((AppEntryApplication) app).setApprovalStatus(status);
                            }
                        },
                        new Consumer<Object>() {
                            @Override
                            public void accept(Object app) {
                                appEntryApplicationService.updateApprovalResult((AppEntryApplication) app);
                            }
                        }
                );
            case 2:
                // 计划申请审核：操作计划申请实体
                AppWorkPlan planApp = appWorkPlanService.selectById(applicationId);
                return new AuditStrategy(
                        planApp,
                        new Consumer2<Object, Integer>() {  // 使用自定义的Consumer2接口
                            @Override
                            public void accept(Object app, Integer status) {
                                ((AppWorkPlan) app).setAuditStatus(status);
                            }
                        },
                        new Consumer<Object>() {
                            @Override
                            public void accept(Object app) {
                                appWorkPlanService.updateSelectiveById((AppWorkPlan) app);
                            }
                        }
                );
            default:
                throw new IllegalArgumentException("不支持的审核类型：" + reviewType);
        }
    }

    /**
     * 审核策略封装类（封装不同审核类型的申请操作）
     */
    @Data
    private static class AuditStrategy {
        private final Object application; // 申请实体（如AppEntryApplication、AppWorkPlanApplication）
        private final Consumer2<Object, Integer> statusSetter; // 申请状态设置器
        private final Consumer<Object> updateAction; // 申请更新操作

        // 更新申请状态
        public void updateApplicationStatus(Integer status) {
            statusSetter.accept(application, status);
            updateAction.accept(application);
        }
    }

    // 自定义双参数Consumer接口
    @FunctionalInterface
    interface Consumer2<T, U> {
        void accept(T t, U u);
    }

    @Override
    public String uplodFile(MultipartFile file) {
        // 获取项目根目录路径
        String projectRootPath = System.getProperty("user.dir");
        // 创建uploads子目录（避免根目录文件混乱）
        String uploadDir = projectRootPath + File.separator + "uploads";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs(); // 递归创建目录
        }

        // 生成唯一文件名（避免重名覆盖）
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        // 构建完整文件路径
        String filePath = uploadDir + File.separator + uniqueFileName;
        File destFile = new File(filePath);

        // 保存文件到磁盘
        try {
            file.transferTo(destFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return filePath;
    }

    @Override
    public int updateFilePath(ClassMeeting classMeeting) {
        int i = classMachService.updateByPrimaryKeySelective(classMeeting);
        return i;
    }

    @Override
    public List<StaffInfoRep> querycheckInList(QuerycheckInListReq req) {

        return Collections.emptyList();
    }

    @Override
    public List<AppWorkTypeDTO> queryCategory(Integer depyId) {
        return appEmpWorkService.workTypeList(depyId);
    }

    @Override
    public EntryApplicationDetailRep queryEntryDetails(WxUser user, Integer id) {
        // 入厂申请基本信息
        EntryApplicationDetailRep rep = new EntryApplicationDetailRep();
        // 人员基本信息
        List<EntryPersonInfo> entryList = new ArrayList<>();
        //获取当前入场申请
        AppEntryApplication entry = appEntryApplicationService.selectByPrimaryKey(id);

        // 获取入场人员
        List<String> person = null;
        if(entry.getEntryPersonId().contains("/")){
            person = Arrays.asList(entry.getEntryPersonId().split("/"));
        }else {
            person =  Arrays.asList(entry.getEntryPersonId());
        }
        List<String> names = new ArrayList<>();
        List<QueryEmpSysIdDto> appEmpIds = sysUserService.getAppEmpEmpNamesIdList(person);
        for (QueryEmpSysIdDto emp : appEmpIds) {
            // 人员信息
            EntryPersonInfo personInfo = new  EntryPersonInfo();
            AppEmpDTO info = appEmpService.getEmpInfo(emp.getAppEmpId());
            SafetyTrainingExamReq safetyTrainingExamReq = convertToExamReq(info);
            personInfo.setName(safetyTrainingExamReq.getName());
            personInfo.setGender(safetyTrainingExamReq.getGender());
            personInfo.setCompany(safetyTrainingExamReq.getCompany());
            personInfo.setPosition(safetyTrainingExamReq.getPosition());
            personInfo.setHardwareNo(safetyTrainingExamReq.getHardwareNumber());
            personInfo.setExamStatus(safetyTrainingExamReq.getExamStatus());
            PlanCategory planCategory = planCategoryService.getPlanCategory(id, emp.getSysUserId());
            if(planCategory != null){
                personInfo.setFactoryPosition(planCategory.getCategoryName());
            }else {
                personInfo.setFactoryPosition("暂无待配置");
            }
            entryList.add(personInfo);
            // 入厂申请基本信息-人员名称
            names.add(info.getEmpName());
        }
        rep.setEntryPersonNameList(names);
        rep.setEntryPersonInfoList(entryList);

        // 获取组长
        rep.setTeamLeader(appEmpService.getEmpInfo(entry.getTeamLeaderId()));
        rep.setApprovalRecord(approvalRecordService.selectRecordByApplyIdAndAuditType(id, ReviewType.ENTRANCE_REVIEW.getValue()));
        // 入场时间
        rep.setEntryTime(entry.getEntryTime());
        // 离场时间
        rep.setLeaveTime(entry.getLeaveTime());
        // 文件
        rep.setFileUrl(entry.getFilePath());
        // 是由
        rep.setReason(entry.getReason());

        return rep;
    }

    @Override
    public AppEntryApplicationWxRep queryEntryInfo(Integer id) {
        AppEntryApplicationWxRep ar = new AppEntryApplicationWxRep();
        //获取当前入场申请
        AppEntryApplication entry = appEntryApplicationService.selectByPrimaryKey(id);
        // 获取入场人员
        List<String> person = null;
        if(entry.getEntryPersonId().contains("/")){
            person = Arrays.asList(entry.getEntryPersonId().split("/"));
        }else {
            person =  Arrays.asList(entry.getEntryPersonId());
        }
        List<String> names = new ArrayList<>();
        List<QueryEmpSysIdDto> appEmpIds = sysUserService.getAppEmpEmpNamesIdList(person);
        for (QueryEmpSysIdDto emp : appEmpIds) {
            AppEmpDTO info = appEmpService.getEmpInfo(emp.getAppEmpId());
            SafetyTrainingExamReq safetyTrainingExamReq = convertToExamReq(info);
            names.add(info.getEmpName());
        }
        // 入厂申请人员姓名
        ar.setEntryPersonName(names);

        // 获取组长
        List<String> leaders = Arrays.asList(String.valueOf(entry.getTeamLeaderId()));
        List<QueryEmpSysIdDto> empNamesIdList = sysUserService.getAppEmpEmpNamesIdList(leaders);
        for (QueryEmpSysIdDto emp : empNamesIdList) {
            AppEmpDTO info = appEmpService.getEmpInfo(emp.getAppEmpId());
            ar.setTeamLeaderId(info.getEmpName());
        }
        ar.setEntryTime(entry.getEntryTime());
        ar.setLeaveTime(entry.getLeaveTime());
        // 分包
        SysDeptDTO sysDeptSubcon = sysDeptService.selectSysDeptById(entry.getSubcontractorId());
        ar.setSubcontractorId(sysDeptSubcon.getName());

        // 总包
        SysDeptDTO sysDeptGeneral = sysDeptService.selectSysDeptById(entry.getGeneralContractorId());
        ar.setGeneralContractorId(sysDeptGeneral.getName());

        // 监理
        SysDeptDTO sysDeptSuperv = sysDeptService.selectSysDeptById(entry.getSupervisionUnitId());
        ar.setSupervisionUnitId(sysDeptSuperv.getName());

        // 业主
        SysDeptDTO sysDeptOwner = sysDeptService.selectSysDeptById(entry.getOwnerUnit());
        ar.setOwnerUnit(sysDeptOwner.getName());

        // 审批
        ar.setApprovalStatus(entry.getApprovalStatus());

        // 上传文件
        ar.setFilePath(entry.getFilePath());

        // 申请事由
        ar.setReason(entry.getReason());
        return ar;
    }

    @Override
    public List<AppMach> queryEquipmentList(Integer deptId) {
        return appMachService.selectByPrimaryKey(deptId);
    }

    @Override
    public List<ApprovalInfoRep> queryApprovalList(Integer applicationId) {
        List<ApprovalInfoRep> approvalInfoReps = new   ArrayList<>();
        List<ApprovalRecord> aps = approvalRecordService.selectRecordByApplyIdAndAuditType(applicationId, ReviewType.ENTRANCE_REVIEW.getValue());
        for (ApprovalRecord ap : aps) {
            ApprovalInfoRep  info = new ApprovalInfoRep();
            // 获取审批人
            List<QueryEmpSysIdDto> empNamesIdList = sysUserService.getAppEmpEmpNamesIdList(Arrays.asList(String.valueOf(ap.getApproverId())));
            for (QueryEmpSysIdDto emp : empNamesIdList) {
                AppEmpDTO appInfo = appEmpService.getEmpInfo(emp.getAppEmpId());
                info.setApproverName(appInfo.getEmpName());
                info.setCompanyName(appInfo.getCorpName());
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            info.setApprovalTime(sdf.format(ap.getApprovalTime()));
            info.setApprovalOpinion(ap.getApprovalOpinion());
            Integer approvalResult = ap.getApprovalResult();
            Integer approverType = ap.getApproverType();
            if (approverType == 4) { // 分包审核
                if (approvalResult == 1) { // 已通过
                    info.setCardTitle("分包已审核");
                    info.setShowActionButtons(false);
                } else if (approvalResult == 2) { // 待审核
                    info.setCardTitle("待分包审核");
                    info.setShowActionButtons(true);
                }
            } else if (approverType == 3) { // 总包审核
                if (approvalResult == 1) {
                    info.setCardTitle("总包已审核");
                    info.setShowActionButtons(false);
                } else if (approvalResult == 2) { // 待审核
                    info.setCardTitle("总包包审核");
                    info.setShowActionButtons(true);
                }
            } else if (approverType == 2) { // 监理审核
                if (approvalResult == 2) { // 待审核
                    info.setCardTitle("待监理单位审核");
                    info.setShowActionButtons(true);
                } else if (approvalResult == 1) {
                    info.setCardTitle("监理已审核");
                    info.setShowActionButtons(false);
                }
            } else if (approverType == 1) { // 业主审核
                if (approvalResult == 2) { // 待审核
                    info.setCardTitle("待业主单位审核");
                    info.setShowActionButtons(true);
                } else if (approvalResult == 1) {
                    info.setCardTitle("业主已审核");
                    info.setShowActionButtons(false);
                }
            }
            approvalInfoReps.add(info);
        }

        return approvalInfoReps;
    }

    /**
     * 获取下一节点类型（如分包的下一节点是总包）
     */
    private Integer getNextNode(Integer currentType) {
        switch (currentType) {
            case 4:
                return 3;
            case 3:
                return 2;
            case 2:
                return 1;
            case 1:
                return 0;
            default:
                return null;
        }
    }
}